package org.springblade.modules.serial;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class NettyServer implements ApplicationListener<ApplicationReadyEvent> {

	private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);


	@Autowired
    private ServerBootstrap serverBootstrap;

    @Autowired
    private EventLoopGroup bossGroup;

    @Autowired
    private EventLoopGroup workerGroup;

    @Value("${netty.port:8088}")
    private int port;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        try {
            ChannelFuture future = serverBootstrap.bind(port).sync();
            logger.info("Netty server started on port {}", port);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.error("Netty server interrupted", e);
            Thread.currentThread().interrupt();
        } finally {
            shutdown();
        }
    }

    private void shutdown() {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}
